<?php
###############   COPYLEFT GPLv3 LICENSE   ###############
##
## JFX Version 0.2.9
## Website Management Software
## www.jfxcms.com
##
## Copyright 2009 GPLv3 - http://www.opensource.org/licenses/gpl-3.0.html
##
## Anthony Gallon
## oi_antz@hotmail.com
##
## Permission is hereby granted to any person having a copy of this software
## to freely use and modify as required so long as the copyright notices
## and branding remain intact.
##
## Full license details available at http://www.jfxcms.com/license
##
###############   COPYLEFT GPLv3 LICENSE   ###############

class JFX_Page extends JFX_Block
{
    /**
     * Contains column name of each column in the database table "pages"
     * @var array
     */
    public $details = array(
        'id' => '',
        'parent_id' => '',
        'lft' => '',
        'rgt' => '',
        'slug' => '',
        'is_published' => '',
        'workspace_id' => '',
        'owner_id' => '',
        'created_tstamp' => '',
        'modified_tstamp' => '',
        'is_default' => '',
        'is_template' => '',
        'domain_id' => '',
        'sorting' => ''
    );

	public $id = null;
	public $title = '';
	public $loaded = false;
    protected $parentChanged = false;
	public $elements = array();
	public $pageid = '';
	public $isPage = true;
	public $isBlock = false;
	public $isTemplate = false;


    /**
     * Use this method to create a new page, for instance inserting a new page to db
     */
    public function __construct($blockId=null, $pageid=''){

		parent::__construct($blockId, $pageid);

        // get some default values that will make it work when saving a new page
        $USER = JFX::registry('JFX_User');
        $SETTINGS = JFX::registry('JFX_Settings');
        $DB = JFX::registry('db');
        $CONFIG = JFX::registry('config');

        $this->set('workspace_id', $USER->workspace);
        $this->set('created_tstamp', time());
        $this->set('modified_tstamp', 0);
        $this->set('is_default', 0);
        $this->set('is_template', 0);
        $this->set('domain_id', $DB->oneValue($CONFIG->dbprefix.'domains', 'id', 'is_default = 1'));

		$CORE = JFX::registry('core');

    }
	public function canDelete(){
		return false;
	}
	public function canMoveUp(){
		return false;
	}
	public function canMoveDown(){
		return false;
	}

	public static function getSubpages($parentid, $workspaceid=''){
		$DB = JFX::registry('db');
        $CONFIG = JFX::registry('config');
		$USER = JFX::registry('JFX_User');
		if($workspaceid==''){
			$workspaceid = $USER->workspace;
		}
		$q = "SELECT id FROM {$CONFIG->dbprefix}pages WHERE workspace_id = '{$workspaceid}' AND parent_id = '{$parentid}' ORDER BY sorting ASC";

		$allPages = $DB->fetchAll($q);
		foreach($allPages as $k=>$row){
			$allPages[$k] = JFX_Block::getBlockById($row['id'], $row['id'], $workspaceid, true, true);
		}
		return $allPages;
	}

	public function __toJson(){
		$pageData = json_decode(parent::__toJson());
		$THEME = JFX::registry('JFX_Theme');
		$pageData->action_buttons = $THEME->getPageActionButtons(preg_replace('/[^0-9]/', '', $this->id));
		
		$allBlocks = $this->elements;
		foreach($allBlocks as $k=>$block){
			$allBlocks[$k]->json = json_decode($block->__toJson());
		}

		$pageData->elements = $allBlocks;

		return json_encode($pageData);

		
	}

	public function addStyle($style){
		$style = trim($style);

		if(is_array($style) || is_object($style)){
			foreach($style as $newStyle){
				$this->addStyle($newStyle);
			}
			return;
		}



		if(!in_array($style, $this->style)){
			$this->style[] = $style;
		}
	}

	public function loadElements($language='', $workspaceid='', $recursive=true, $loadObject=true){
		if(!$this->loaded){
			$this->loaded = true;
			$this->elements = self::getBlocks($this->details['id'], $language, $workspaceid, $recursive, $loadObject);
		}
	}

	public static function getBlocks($pageid, $language='', $workspaceid='', $recursive=true, $loadObject=true){
		$DB = JFX::registry('db');
		$CONFIG = JFX::registry('config');
		$USER = JFX::registry('JFX_User');
		
		if($language==''){
			$language = $USER->lang;
		}
		if($workspaceid==''){
			$workspaceid = $USER->workspace;
		}

		$workspaceid = (int) $workspaceid;
		$pageid = $DB->escape($pageid);

		$q = "SELECT * FROM {$CONFIG->dbprefix}blocks WHERE page_id = '{$pageid}' AND workspace_id = '{$workspaceid}' AND page_parent = 1 ORDER BY sorting ASC";

		$allBlocks = $DB->fetchAll($q);

		foreach($allBlocks as $k=>$blockData){
			$block = JFX_Block::getBlockById($blockData['id'], $pageid, $workspaceid, $recursive, $loadObject);
			if($block->id==''){
				unset($allBlocks[$k]);
				continue;
			}
			$allBlocks[$k] = $block;
		}
		return $allBlocks;

	}


    public static function getUniqueSlug($preferredSlug, $workspaceid, $domainid){
        $DB = JFX::registry('db');
        $CONFIG = JFX::registry('config');
        
        if($DB->countRows($CONFIG->dbprefix.'pages', "workspace_id = '{$workspaceid}' AND domain_id = '{$domainid}' AND slug = '{$slug}'")>0){
            $newPreferredSlug .= '1';
            return self::getUniqueSlug($newPreferredSlug);
        }else{
            // not already existing
            return $preferredSlug;
        }

    }

    public function loadById($id, $pageid='', $workspaceid=''){
		return parent::loadById($id, $id, $workspaceid);
		if(true || trim($this->title)==''){
			$this->title = 'Page '.$this->pageid;
		}
    }



    public function get($key=null){
        $retArray = $this->details;
		$retArray['title'] = $this->title;
		
        if($key!==null && array_key_exists($key, $retArray)) return $retArray[$key];
        else return $retArray;
    }

    public function set($key, $value=null){
        if(is_array($key)){
            foreach($key as $k=>$v){
                $this->set($k, $v);
            }
        }else if(!is_string($key)){
            return false;
        }else{
            if($key=='parent_id'){
                return $this->setParent($value);
            }
            if(array_key_exists($key, $this->details)) $this->details[$key] = $value;
            if($key==='title'){
                $this->title = $title;
            }
			if(isset($this->$key)){
				$this->$key = $value;
			}
        }
        return true;
    }

	public function render(){
		return;
	}

	public function addTemplateBlock($templateId, $pageid=''){
		return parent::addTemplateBlock($templateId, $pageid);
	}

    public function setParent($newParentId){
        if($this->hasDescendant($newParentId)){
            return false;
        }else{
            $this->details['parent_id'] = $newParentId;
            $this->parentChanged = true;
            return true;
        }
    }

	public function hasDescendant($pageId){
		$DB = JFX::registry('db');
		$CONFIG = JFX::registry('config');
		$pageId = (int) $pageId;
		$lft = (int) $this->details['lft'];
		$rgt = (int) $this->details['rgt'];
		if($DB->countRows($CONFIG->dbprefix.'pages', "id = {$pageId} AND lft >= {$lft} AND rgt <= {$rgt}")>0){
			// yes it has a descendant with that id
			return true;
		}else{
			return false;
		}

	}




    public function canSave(){
        if($this->get('workspace_id')!='' && $this->get('slug')!='' && $this->get('domain_id')!=''){
            return true;
        }
        return false;
    }

    public function save(){
        $DB = JFX::registry('db');
        $CONFIG = JFX::registry('config');
        $CORE = JFX::registry('JFX_Core');
        if(!$this->canSave()) return false;
        $error = false;
        if($this->get('id')==''){
            // inserting
			$insertArray = $this->get();
			unset($insertArray['title']);
            $pageid = $DB->insert($CONFIG->dbprefix.'pages', $insertArray);
            if(intval($pageid)===0){
                $error = true;
            }else{
                $error = false;
            }
            $this->set('id', $pageid);
            
        }else{
            // updating
            $dbParams = $this->get();
            $pageid = $dbParams['id'];
            unset($dbParams['id'], $dbParams['title']);
            $DB->update($CONFIG->dbprefix.'pages', $dbParams, "id = '{$pageid}'");
        }

        if($this->parentChanged){
            self::rebuildHeirarchy();
            $this->parentChanged = false;
        }

        if(!$error){
            $CORE->updateContentLang('heading', $pageid, $this->title);
        }

        return !$error;
        
    }

    /**
     * Rebuild lft/rgt heirarchy values from any given node. Important to provide correct $left parameter or you will screw up the db! If in doubt, just use default values.
     * @param int $parentId
     * @param int $left
     * @return int $right
     */
    public static function rebuildHeirarchy($parentId=0, $left=0){
        $DB = JFX::registry('db');
        $CONFIG = JFX::registry('config');
        
        $right = $left+1;

        $q = "SELECT id FROM {$CONFIG->dbprefix}pages WHERE parent_id = '{$parentId}' ORDER BY sorting ASC";
        $pages = $DB->fetchAll($q);

        foreach($pages as $row){
            $right = self::rebuildHeirarchy($row['id'], $right);
        }

        if($parentId>0){
            $DB->update($CONFIG->dbprefix.'pages', array('lft'=>$left, 'rgt'=>$right), "id = '{$parentId}'");
        }

        return $right+1;

    }


}
